package com.chhuang.uresource.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chhuang.uresource.conts.SysConstants;
import com.chhuang.uresource.po.ChLog;
import com.chhuang.uresource.po.ChUser;
import com.chhuang.uresource.service.IChLogService;
import com.chhuang.uresource.service.IChUserService;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;
import com.chhuang.utils.string.Md5Util;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/system/login")
public class LoginController {
	private static final Log log = LogFactory.getLog(LoginController.class);

	@Autowired
	private IChUserService chUserService;
	@Autowired
	private IChLogService chLogService;
	
	/**
	 * 登录
	 * @param username
	 * @param password
	 * @param checkCode
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(method=RequestMethod.POST)
	public Object login(String username, String password, String verificationCode, HttpServletRequest request) throws Exception {
		JSONObject json = new JSONObject();

		HttpSession session = request.getSession(false);
		if(session!=null){
			
			if(Assert.isValidString(username) && Assert.isValidString(password) && Assert.isValidString(verificationCode)){//参数不空
				String key = SysConfig.getValue(SysConstants.Config.CHECK_CODE);
				String sessionCode = (String) session.getAttribute(key);
				if(Assert.isValidString(sessionCode) && sessionCode.equalsIgnoreCase(verificationCode)){//验证码正确
					List<ChUser> users = chUserService.findByUsername(username);
					if(Assert.isValidCollection(users) && users.get(0)!=null){//用户存在 
						ChUser user = users.get(0);
						if(user.getPassword().equals(Md5Util.md5(password, username))) {//密码正确
							json.put(SysConstants.Status.SUCCESS, true);
							session.setAttribute(SysConstants.USER_ID, user.getUserId());
							session.setAttribute(SysConstants.USERNAME, user.getUsername());
							writeLog(user.getUserId(), user.getUsername(), "登录");
						}else {
							json.put(SysConstants.Status.SUCCESS, false);
							json.put(SysConstants.Status.RESULT, "密码不正确");
						}
					}else {
						json.put(SysConstants.Status.SUCCESS, false);
						json.put(SysConstants.Status.RESULT, "用户名不存在");
					}
				}else {
					json.put(SysConstants.Status.SUCCESS, false);
					json.put(SysConstants.Status.RESULT, "验证码有误");
				}
			}else {
				json.put(SysConstants.Status.SUCCESS, false);
				json.put(SysConstants.Status.RESULT, "传入参数有误");
			}

		
		}else {
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "验证码已过期，请点击验证码图片刷新");
		}
		
		log.debug(json);
		return json;
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/logout", method={RequestMethod.GET, RequestMethod.POST})
	public String logout(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession(false);
		if(session!=null) {
			String userId = (String) session.getAttribute(SysConstants.USER_ID);
			String username = (String) session.getAttribute(SysConstants.USERNAME);
			session.removeAttribute(SysConstants.USER_ID);
			session.removeAttribute(SysConstants.USERNAME);
			writeLog(userId, username, "退出登录");
		}
		return "redirect:/pages/system/login.html";
	}
	
	/**
	 * 记录日志
	 * @param user
	 * @param logContent
	 * @throws Exception
	 */
	private void writeLog(String userId, String username, String logContent) throws Exception {
		ChLog log = new ChLog();
		log.setUserId(userId);
		log.setUsername(username);
		log.setLog(logContent);
		log.setCreateTime(new Date());
		chLogService.save(log);
	}
	
	
	public static void main(String[] args) {
		System.out.println(Md5Util.md5("chhuang123", "chhuang"));
	}
}
